<template>
  <div>
    <!-- <div class="title">故障处理字段下拉值配置</div> -->
    <a-card v-for="(item, index) in allData" class="card" :key="index">
      <template #title>
        {{ item.configName }}
        <a-button
          type="link"
          :size="size"
          @click="isEdit(index)"
          v-if="!item.isEditBoolean"
        >
          <template #icon> <FormOutlined /> </template
        ></a-button>
        <template v-else>
          <a-button
            size="small"
            style="margin-left: 10px"
            @click="cancel(index)"
            >取消</a-button
          >
          <a-button
            type="primary"
            size="small"
            style="margin-left: 10px"
            @click="save(item, index)"
            >保存</a-button
          >
        </template>
      </template>

      <template v-if="item.faultConfigEntityList.length > 0">
        <template v-for="(tag, idx) in item.faultConfigEntityList" :key="tag">
          <a-tag
            :closable="item.isEditBoolean"
            @close="handleClose(index, tag)"
            color="green"
            class="tag"
          >
            {{ tag.name }}
          </a-tag>
        </template>
      </template>
      <template
        v-else-if="
          item.faultConfigEntityList.length === 0 && !item.isEditBoolean
        "
      >
        <a-empty :image="simpleImage" />
      </template>

      <a-input
        v-if="item.inputVisible"
        :ref="(el) => (inputRef[idx] = el)"
        v-model:value="item.inputValue.name"
        type="text"
        size="small"
        :style="{ width: '78px' }"
        @blur="handleInputConfirm(index)"
        @keyup.enter="handleInputConfirm(index)"
      />
      <a-tag
        v-else-if="!item.inputVisible && item.isEditBoolean"
        style="border-style: dashed"
        @click="showInput(index)"
      >
        <plus-outlined />
        新增
      </a-tag>
    </a-card>
  </div>
</template>
<script setup>
// 
import { FormOutlined, PlusOutlined } from "@ant-design/icons-vue"
import { Empty } from 'ant-design-vue'
import { cloneDeep } from "lodash-es"
import { FAULT_REGISTRATION_TYPE } from "@/constants/faultRegistration.js"
const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE
const $api = inject("$api")

const inputRef = ref([])
const props = defineProps({
  nowTab: {
    type: Number,
    default: null,
  },
})
const nowTab = ref(null)
watch(
  () => props.nowTab,
  (val) => {
    if (val) {
      nowTab.value = val
    }
  },
  {
    immediate: true,
  }
)
const isEdit = (index) => {
  // 在开始编辑前，先保存当前数据状态，以便取消时恢复
  cloneData.value = cloneDeep(allData.value)
  allData.value[index].isEditBoolean = true
}

const showInput = async (index) => {
  allData.value[index].inputVisible = true
  await nextTick()
  if (inputRef.value[index]) {
    inputRef.value[index].focus()
  }
}
const save = async (item, index) => {
  /* if (item.faultConfigEntityList.length === 0) {
    message.error("至少需配置一个类别")
    return
  } */
  let params = {
    configType: nowTab.value,
    type: item.type,
    faultConfigEntityList: item.faultConfigEntityList,
  }
  let res = await $api.faultConfig(params)
  if (res && res.code === 0) {
    allData.value[index].isEditBoolean = false
    getList(item.type, index)
  }
}
const allData = ref([]) // 用于存储整理后的数据
const getAllData = async () => {
  // 初始化allData，根据FAULT_REGISTRATION_TYPE创建基础结构
  allData.value = FAULT_REGISTRATION_TYPE.filter((e) => e.type <= 3).map(
    (item) => {
      return {
        type: item.type,
        configName: item.configName,
        inputVisible: false,
        inputValue: { name: "", type: item.type, configType: nowTab.value },
        isEditBoolean: false,
        faultConfigEntityList: [],
      }
    }
  )

  // 创建所有请求的Promise数组
  console.log("item", allData.value)
  const promises = allData.value.map((item, index) => getList(item.type, index))

  await Promise.all(promises)
  console.log("整理后的数据结构：", allData.value)
}

const getList = async (type, index) => {
  let params = {
    configType: nowTab.value,
    type: type,
  }
  let res = await $api.faultConfigList(params)
  if (res && res.data) {
    allData.value[index].faultConfigEntityList = res.data
  }
}
// 需要实现handleClose和handleInputConfirm函数
const handleClose = (index, tag) => {
  //tagArr.value = tagArr.value.filter((t) => t.name !== tag.name)
  allData.value[index].faultConfigEntityList = allData.value[
    index
  ].faultConfigEntityList.filter((t) => t.name !== tag.name)
}

const handleInputConfirm = (index) => {
  if (
    allData.value[index].inputValue.name &&
    allData.value[index].faultConfigEntityList.filter(
      (t) => t.name === allData.value[index].inputValue.name
    ).length === 0
  ) {
    allData.value[index].faultConfigEntityList = [
      ...allData.value[index].faultConfigEntityList,
      allData.value[index].inputValue,
    ]
  }
  allData.value[index].inputVisible = false
  allData.value[index].inputValue = {
    name: "",
    type: allData.value[index].type,
    configType: nowTab.value,
  }
}
const cloneData = ref([])

const cancel = (index) => {
  allData.value[index].faultConfigEntityList =
    cloneData.value[index].faultConfigEntityList
  allData.value[index].isEditBoolean = false
}
onMounted(async () => {
  getAllData()
})
</script>
<style lang="less" scoped>
.title {
  font-size: 20px;
}
.card {
  margin-top: 20px;
}
.card:first-child {
  margin-top: 0;
}
.tag {
  margin-bottom: 10px;
}
</style>
